package com.sky.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisKeyConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author wang
 * @since 2023-07-06
 */
@RestController
@RequestMapping("/admin/setmeal")
@Transactional
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_SETMEAL_BY_CATEGORYID,key = "#setmealDTO.categoryId")   //清理缓存
    @PostMapping
    public Result save(@RequestBody SetmealDTO setmealDTO){
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealService.save(setmeal);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.stream().map((setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
            return setmealDish;
        })).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return Result.success();
    }

    @GetMapping("/page")
    public Result page(SetmealPageQueryDTO setmealPageQueryDTO){
        Page<SetmealVO> setmealVOPage = new Page<>(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        setmealVOPage = setmealService.pageSetmeal(setmealVOPage,setmealPageQueryDTO);
        return Result.success(setmealVOPage);
    }

    /**
     * 起售套餐要保证套餐内的所有菜品存在而且都是起售状态才可以起售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_SETMEAL_BY_CATEGORYID,allEntries = true)   //清理所有缓存
    public Result updataStatus(@PathVariable Integer status, Long id){
        return setmealService.updateStatus(status,id);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id){
        Setmeal setmeal = setmealService.getById(id);
        SetmealDTO setmealDTO = new SetmealDTO();
        BeanUtils.copyProperties(setmeal,setmealDTO);
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);
        setmealDTO.setSetmealDishes(setmealDishList);
        return Result.success(setmealDTO);
    }

    @PutMapping
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_SETMEAL_BY_CATEGORYID,allEntries = true)   //清理所有缓存
    public Result updata(@RequestBody SetmealDTO setmealDTO){
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealService.updateById(setmeal);
        //删除套餐与菜品关系，重新建立两者关系
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return Result.success();
    }

    @DeleteMapping
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_SETMEAL_BY_CATEGORYID,allEntries = true)   //清理所有缓存
    public Result delete(@RequestParam("ids") List<Long> ids){
        if (ids == null || ids.size() == 0){
            return Result.error("请选择套餐");
        }
        //判断菜品是否处于起售状态
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        setmealService.removeByIds(ids);
        //删除套餐与菜品关系表数据
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
        return Result.success();
    }
}
